
//---------------------------------------------------------------------------
#include "entities/pg1_sprite.h"
//---------------------------------------------------------------------------
#include "rendering/pg1_renderer.h"
#include "animation/pg1_timer.h"
#include "animation/pg1_animation.h"
//---------------------------------------------------------------------------
#include <d3dx9.h>
//---------------------------------------------------------------------------
using namespace pg1;
//---------------------------------------------------------------------------
Sprite::Sprite ()
:
Entity2D(),
m_kTexture(NoTexture),
m_pakVertices( new TexCoordVertex[4] ),
m_pkAnimation(NULL),
m_uiPreviousFrame( std::numeric_limits<unsigned int>::max() )
{
	m_pakVertices[0].x = -0.5;	m_pakVertices[0].y = 0.5;	m_pakVertices[0].z = 0.0f;
	m_pakVertices[1].x = 0.5;	m_pakVertices[1].y = 0.5;	m_pakVertices[1].z = 0.0f;
	m_pakVertices[2].x = -0.5;	m_pakVertices[2].y = -0.5;	m_pakVertices[2].z = 0.0f;
	m_pakVertices[3].x = 0.5;	m_pakVertices[3].y = -0.5;	m_pakVertices[3].z = 0.0f;

	// texture coordinates
	m_pakVertices[0].u = 0.0;	m_pakVertices[0].v = 0.0;
	m_pakVertices[1].u = 1.0;	m_pakVertices[1].v = 0.0;
	m_pakVertices[2].u = 0.0;	m_pakVertices[2].v = 1.0;
	m_pakVertices[3].u = 1.0;	m_pakVertices[3].v = 1.0;
}
//---------------------------------------------------------------------------
Sprite::~Sprite ()
{
	m_pkAnimation = NULL;

	delete[] m_pakVertices;
	m_pakVertices = NULL;
}
//---------------------------------------------------------------------------
void Sprite::setTexCoords (float fU1, float fV1, 
						   float fU2, float fV2, 
						   float fU3, float fV3, 
						   float fU4, float fV4)
{
	m_pakVertices[0].u = fU1;	m_pakVertices[0].v = fV1;
	m_pakVertices[1].u = fU2;	m_pakVertices[1].v = fV2;
	m_pakVertices[2].u = fU3;	m_pakVertices[2].v = fV3;
	m_pakVertices[3].u = fU4;	m_pakVertices[3].v = fV4;
}
//---------------------------------------------------------------------------
void Sprite::draw (Renderer& rkRenderer) const
{
	rkRenderer.setCurrentTexture(m_kTexture);
	rkRenderer.setMatrix( World, transformationMatrix() );
	rkRenderer.draw(m_pakVertices, pg1::TriangleStrip, 4);
}
//---------------------------------------------------------------------------
void Sprite::update (Timer& rkTimer)
{
	if(!m_pkAnimation) {
		return;
	}

	// update animation
	m_pkAnimation->update(rkTimer);

	// if frame changed, update sprite
	unsigned int uiCurrentFrame = m_pkAnimation->currentFrame();
	
	if(uiCurrentFrame != m_uiPreviousFrame) {
		
		const Animation::Frame& rkFrame = m_pkAnimation->frames()[uiCurrentFrame];
		setTexCoords(rkFrame.u1, rkFrame.v1, rkFrame.u2, rkFrame.v2, 
					 rkFrame.u3, rkFrame.v3, rkFrame.u4, rkFrame.v4
		);
	}
}
//---------------------------------------------------------------------------
